import codecs
import sys

from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData

from .codegen import CodeGenerator


def run(url, outfile=None, flask=True, tables=None, schema=None, noviews=False, noindexes=False, noconstraints=False, nojoined=False,
        noinflect=False, noclasses=False, nobackrefs=False,  ignore_cols=None, nocomments=False):
    ''' 运行程序
    --
        @param url: mysql+pymysql://user:pwd@url/tablename
        @param outfile: 输出路径
        @param flask: 是否在flask中使用
        @param tables: 只生成指定表
        @param schema: 编码
        @param noviews: 忽略视图
        @param noindexes: 忽略索引
        @param noconstraints: 忽略约束
        @param nojoined: 忽略表连接
        @param noinflect:  不转换表名
        @param noclasses: 不生成类，只生成表
        @param nobackrefs: 不包括背景引用
        @param ignore-cols: 不检查外键
        @param nocomments: 不显示注释
    '''
    engine = create_engine(url)
    metadata = MetaData(engine)
    tables = tables.split(',') if tables else None
    ignore_cols = ignore_cols.split(',') if ignore_cols else None
    metadata.reflect(engine, schema, not noviews, tables)
    outfile = codecs.open(
        outfile, 'w', encoding='utf-8') if outfile else sys.stdout
    generator = CodeGenerator(metadata, noindexes, noconstraints,
                              nojoined, noinflect, nobackrefs,
                              flask, ignore_cols, noclasses, nocomments)
    generator.render(outfile)
